// 用户相关的redux子模块
// 导入 createSlice 创建一个redux切片，并配置 该切片名称|该状态切片的初始状态值|该状态切片的reducers(用于修改切片状态的同步方法集)
import { createSlice } from "@reduxjs/toolkit";
// 导入 封装后的请求模块
import { removeToken } from "@/utils";
import { setToken as _setToken, getToken } from "@/utils";
import { getProfileAPI, loginAPI } from "@/apis/user";

// 创建切片实例
const userStore = createSlice({
    // 该切片名称
    name: 'user',
    // 该状态切片的初始状态值
    initialState: {
        token: getToken() || '',
        userInfo: {},
    },
    // 该状态切片的reducers
    reducers: {
        /**
         * 设置token
         * @param {*} state 所属切片的状态集
         * @param {*} action 调用方法时传入的参数为action的载荷，即action.payload
         */
        setToken(state, action) {
            state.token = action.payload
            _setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state) {
            state.token = ''
            state.userInfo = {}
            removeToken()
        }
    }
})

// 解构出actionCreater
const { setToken, setUserInfo, clearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 封装异步请求方法
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        // 异步请求
        const res = await loginAPI(loginForm)
        // 提交同步方法存入数据
        dispatch(setToken(res.data.token))
    }
}

const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getProfileAPI()
        dispatch(setUserInfo(res.data))
    }
}

// 按需导出actionCreater
export { setToken, clearUserInfo, fetchLogin, fetchUserInfo }

// 默认导出reducer
export default userReducer
